import React from 'react';

import { connect } from 'dva'
import moment from 'moment'

import Title from 'components/Title'
import Chart from 'components/Chart'

@connect(({ gis }) => ({ ...gis }))
class Age extends React.Component {
  static defaultProps = {
    abstractConf: {
      list: [
        { label: '0~2年', key: 'year_0_2', dateRange: [0, 2] },
        { label: '2~3年', key: 'year_2_3', dateRange: [2, 3] },
        { label: '3~6年', key: 'year_3_6', dateRange: [3, 6] },
      ],
      chart: {
        type: 'Pie',
        other: { formatType: 'onlyPercent' },
        columns: {
          name: '', field: [{name: 'name', value: 'value'}]
        }
      },
    }
  }

  constructor(props) {
    super(props);

    this.state = {
      dataSource: []
    }
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    await this.setDateIndicators()
  }

  // 人工维护数据：指标逻辑
  queryIndicators = async (params) => {
    const { props } = this;
    let payload = {}
    
    const { dateRange, key, label: name } = params;
    const [ start, end ] = dateRange;
    // 处理时间
    const startDate = moment().add(end*-1, 'y').format("YYYY-MM-D");
    const endDate = moment().add(start*-1, 'y').format("YYYY-MM-D");
    // where条件拼接
    const where = `建设年代 >= '${startDate}' and 建设年代 <= '${endDate}'`;
    // 处理 outStatistics，注意别外 value
    const outStatistics = `[{"statisticType":"SUM","onStatisticField":"管长","outStatisticFieldName": value}]`
    // 合并条件
    Object.assign(payload, { key, where, outStatistics })
    await props.dispatch({ type: 'gis/queryAge', payload })
  }

  setDateIndicators = () => {
    const { list } = this.props.abstractConf;
    list.map(ele => {
      this.queryIndicators(ele);
    })
  }

  render() {
    const { props } = this;
    const { chart, list } = props.abstractConf;
    const { type, color, columns, ...other } = chart;

    let dataSource = list.map(ele => {
      const { label: name, key } = ele;
       // 返回结果 value 与 outStatistics别名相同
      const value = props[`AgeResource${key}`] && (props[`AgeResource${key}`].value || props[`AgeResource${key}`].value === 0) ? props[`AgeResource${key}`].value : 0;
      return { name , value };
    });

    return (
      <Title title={'管龄分析图'} style={{ 'padding': '2%' }}>
        <Chart
            type={type}
            color={color}
            columns={columns}
            dataSource={dataSource}
            other={other}
            style={{ paddingBottom: '20px' }}
          />
      </Title>
    )
  }
}

export default Age;